<template>
  <div class="trend-chart-container">
    <div class="chart-header">
      <!-- <span>地区发展趋势</span> -->
      <el-select v-model="selectedIndicator" placeholder="选择指标" size="small" style="width: 180px">
        <el-option label="GDP增长率" value="gdp" />
        <el-option label="就业率变化" value="employment" />
        <el-option label="收入增长" value="income" />
        <el-option label="生活成本" value="cost" />
        <el-option label="教育资源" value="edFund" />
      </el-select>
    </div>
    <CommonChart :options="chartOptions" height="calc(100% - 24px)" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue"
import type { EChartsOption } from "echarts"
import { CommonChart } from "./index"
import { getTrendDataApi } from "@/interface"

import { colorManager } from "@/utils/colorMap"
interface Props {
  provinces: string[]
}
const props = withDefaults(defineProps<Props>(), {})

const selectedIndicator = ref("gdp")
const trendData = ref<any>(null)

const filteredProvinceTrends = computed(() => {
  if (props.provinces.length === 0) {
    return trendData.value?.provinces || []
  }

  return trendData.value.provinces.filter((item: any) => {
    // 获取省份名称（去掉"省"或"市"后缀）
    const provinceName = item.name.replace(/[省市]$/, "")
    // 检查是否在选中的省份列表中
    return props.provinces.some(selectedProvince => selectedProvince === provinceName || selectedProvince === item.name)
  })
})

// 指标映射
const indicatorMap: Record<string, any> = {
  gdp: {
    key: "GDP",
    label: "GDP",
    description: "地区生产总值增长趋势",
    unit: "亿元"
  },
  employment: {
    key: "employment",
    label: "就业率",
    description: "就业人数变化趋势",
    unit: "万人"
  },
  income: {
    key: "income",
    label: "收入水平",
    description: "居民人均可支配收入变化",
    unit: "元"
  },
  cost: {
    key: "cost",
    label: "生活成本",
    description: "居民消费支出变化",
    unit: "元"
  },
  edFund: {
    key: "edFund",
    label: "教育资源",
    description: "教育经费投入变化",
    unit: "万元"
  }
}

const chartOptions = computed<EChartsOption>(() => {
  if (!trendData.value) return {}

  const currentIndicator = indicatorMap[selectedIndicator.value]
  const nationalData = trendData.value.national[currentIndicator.key]
  // 根据 provinces 筛选省份数据
  // const filteredProvinceTrends = trendData.value.provinces.filter((item: any) => props.provinces.includes(item.name))

  const otherSeries = filteredProvinceTrends.value.map((item: any) => {
    return {
      name: item.name,
      type: "line",
      data: item.data[currentIndicator.key].data.map((item: any) => item.value),
      itemStyle: {
        color: colorManager.getColor(item.name)
      },
      lineStyle: {
        color: colorManager.getColor(item.name)
      }
    }
  })

  return {
    legend: {
      type: "scroll",
      top: "3%",
      right: "0%",
      width: "100%",
      pageIconSize: 10,
      pageTextStyle: {
        color: "#666"
      },
      textStyle: {
        color: "#666"
      },
      icon: "circle",
      itemStyle: {
        borderWidth: 0
      },
      data: [
        {
          name: "全国平均",
          itemStyle: {
            color: "#409EFF"
          }
        },
        ...filteredProvinceTrends.value.map((item: any) => ({
          name: item.name,
          itemStyle: {
            color: colorManager.getColor(item.name)
          }
        }))
      ]
    },
    tooltip: {
      trigger: "axis",
      formatter: (params: any) => {
        // 获取年份
        const year = params[0].axisValue

        // 构建tooltip内容
        let content = `<div style="font-weight: bold; margin-bottom: 5px;">${year}年</div>`

        // 添加每个省份的数据
        params.forEach((param: any) => {
          // 获取省份名称和数值
          const provinceName = param.seriesName
          const value = param.value

          // 使用省份对应的颜色
          const color = param.color

          // 添加到内容中
          content += `<div style="display: flex; justify-content: space-between; margin: 3px 0; align-items: center;">
        <span style="display: inline-block; width: 10px; height: 10px; background-color: ${color}; margin-right: 5px; border-radius: 50%;"></span>
        <span style="margin-right: 15px;">${provinceName}</span>
        <span style="font-weight: 500;">${value} ${currentIndicator.unit}</span>
      </div>`
        })

        content = `<div style="overflow: auto; height: 200px;">${content}</div>`

        return content
      },
      backgroundColor: "rgba(255, 255, 255, 0.9)",
      borderColor: "#ccc",
      borderWidth: 1,
      textStyle: {
        color: "#333"
      },
      padding: [10, 15],
      confine: true,
      enterable: true
    },
    xAxis: {
      type: "category",
      data: nationalData.data.map((item: any) => item.year)
    },
    yAxis: {
      type: "value",
      name: currentIndicator.unit
    },
    series: [
      {
        name: "全国平均",
        type: "line",
        data: nationalData.data.map((item: any) => item.value),
        markPoint: {
          data: [
            { type: "max", name: "最大值" },
            { type: "min", name: "最小值" }
          ]
        },
        markLine: {
          data: [{ type: "average", name: "平均值" }]
        }
      },
      ...otherSeries
    ],
    grid: {
      left: "3%",
      right: "4%",
      bottom: "0%",
      top: "25%",
      containLabel: true
    }
  }
})

onMounted(async () => {
  try {
    const response = await getTrendDataApi()
    trendData.value = response.data
  } catch (error) {
    console.error("获取趋势数据失败:", error)
  }
})
</script>

<style lang="scss" scoped>
.trend-chart-container {
  width: 100%;
  height: 100%;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  // height: 40px;
}
</style>
